package com.freely.data.database;

import com.freely.component.activity.FreelyApplication;
import com.freely.data.database.DAO.ChatRecordDAO;
import com.freely.data.database.DAO.ChatRecordMainDao;
import com.freely.data.database.DAO.GroupDAO;
import com.freely.data.database.DAO.GroupMainDao;
import com.freely.data.database.DAO.MessageDAO;
import com.freely.data.database.DAO.UserDAO;
import com.freely.data.database.DAO.UserGroupRelationDAO;
import com.freely.data.database.converters.DateConverter;
import com.freely.data.entities.ChatRecord;
import com.freely.data.entities.ChatRecordMain;
import com.freely.data.entities.Group;
import com.freely.data.entities.GroupMain;
import com.freely.data.entities.Message;
import com.freely.data.entities.User;
import com.freely.data.entities.UserGroupRelation;

import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.TypeConverters;

@Database(entities = {
        ChatRecord.class,
        ChatRecordMain.class,
        Group.class,
        GroupMain.class,
        Message.class,
        User.class,
        UserGroupRelation.class
    }, version = 1
)
@TypeConverters({DateConverter.class})
public abstract class FreelyDatabase extends RoomDatabase {

    public abstract ChatRecordDAO chatRecordDAO();
    public abstract ChatRecordMainDao chatRecordMainDao();
    public abstract GroupDAO groupDAO();
    public abstract GroupMainDao groupMainDao();
    public abstract MessageDAO messageDAO();
    public abstract UserDAO userDAO();
    public abstract UserGroupRelationDAO userGroupRelationDAO();

    public static FreelyDatabase getInstance() {
        return Builder.build();
    }

    private static class Builder {
        private static FreelyDatabase INSTANCE;
        static FreelyDatabase build() {
            if (INSTANCE == null) {
                INSTANCE = newInstance();
                return INSTANCE;
            }
            if (INSTANCE.isOpen()) {
                return INSTANCE;
            }
            INSTANCE = newInstance();
            return INSTANCE;
        }

        private static FreelyDatabase newInstance() {
            return Room.databaseBuilder(
                    FreelyApplication.getContext(),
                    FreelyDatabase.class,
                    "freely.db"
            ).build();
        }
    }
}
